<?php

namespace app\admin\controller\user;

use addons\shopro\service\commission\Agent as AgentService;
use addons\shopro\service\user\UserAuth;
use app\admin\model\shopro\commission\Agent;
use app\common\controller\Backend;
use app\common\library\Auth;
use Exception;
use fast\Random;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\exception\PDOException;
use think\Validate;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }


    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }

    public function daoruAll()
    {
        header("content-type:text/html;charset=utf-8");
        //上传excel文件
        $filePath=ROOT_PATH  ."public"."/uploads/20240105/22222.xlsx";
        $spreadsheet = IOFactory::load($filePath);
        $sheetData = $spreadsheet->getActiveSheet()->toArray(true, true, true, true, true);
        $row_num = count($sheetData);
        //从第二行开始做for循环
        $insert=[];
        $userDefaultConfig = sheep_config('shop.user');
        $userModel=new \app\admin\model\User();
        for ($i = 2; $i <= $row_num; $i++) {
            //$import_data[$i]['tj'] = $sheetData[$i]['F'];//推荐人
            $params['nickname'] = $sheetData[$i]['C'];
            $mobile = trim($sheetData[$i]['D']);
            $params['username'] = $mobile;
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $mobile='';
            }
            $params["mobile"]=$mobile;
            $params['avatar'] = $userDefaultConfig['avatar'];
            $password = substr($sheetData[$i]['D'], -6);
            $password ="a".$password;
            $params['salt']=Random::alnum();
            $params['jointime']=time();
            $params['status']='normal';
            $params['password'] = $this->getEncryptPassword($password, $params['salt']);
            $level= $sheetData[$i]['B'];
            $level= trim($level);
            $params["commiss_level"]=1;
            if($level=="VIP") $params["commiss_level"]=2;
            if($level=="县代") $params["commiss_level"]=3;
            if($level=="市代") $params["commiss_level"]=4;
            if($level=="总代" || $level=='省代') $params["commiss_level"]=5;
            if($level=="特约合伙人") $params["commiss_level"]=6;
            if($level=="联合创建人") $params["commiss_level"]=7;
            if($level=="分红股东") $params["commiss_level"]=8;
            $params["commiss_mobile"]=$sheetData[$i]['E'];
            $insert[]=$params;
        }
        $userModel->allowField(true)->saveAll($insert);
    }

    public function level(){

        /*$model=new  \app\admin\model\User();
        $user_ids= $model->alias("user")
            ->join("user t2","user.id=t2.parent_user_id","left")
            ->where("t2.id is null")
            ->column("user.id");*/
        $user_ids=Agent::where("level >=8")->column("user_id");
        foreach ($user_ids as $id){
            \think\Queue::push('\addons\shopro\job\Monthly@level', ['user_id' => $id], 'shopro');
        }
        echo 2222;exit;
        if(!empty($user_ids)){
            $users =$model->whereIn("id",$user_ids)->select();//查找最底层用户
            
            foreach ($users as $user){
                $agent = new AgentService($user);
                
                $agent->runAgentUpgradePlan(true,0);
            }
        }
    }
    public function levels(){
        $model=new  \app\admin\model\User();
    }
    /**
     * 处理nl_shopro_commission_agent表
     * */
    public function check_agent(){
        $model=new  \app\admin\model\User();
        /*$user=$model->where("commiss_mobile is not null and commiss_mobile !=''")->where("parent_user_id is null")->select();
        $commiss=[];
        if(!empty($user)){
            foreach ($user as $v){
                $parent_user=$model->where(["username"=>$v["commiss_mobile"]])->find();
                if(!empty($parent_user)){
                    $model->where(["id"=>$v["id"]])->update(["parent_user_id"=>$parent_user["id"]]);
                }
            }
        }*/

        $time=time();
        $user=$model->select();
        foreach ($user as $v){
            $commiss[]=[
                "user_id"=>$v["id"],
                "level"=>$v["commiss_level"]??1,
                "createtime"=>$time,
            ];
        }
        Agent::insertAll($commiss);
    }
}
